<template>
  <div class="myinfo">
    <el-row type="flex" class="row-bg">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <div style="
              margin-top: 20%;
              font-weight: 700;
              font-size: 18px;
              color: rgb(64, 158, 255);
            ">
            个人信息
          </div>
          <el-upload style="margin-left: 40px; margin-top: 25px" class="avatar-uploader" action="string"
            :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadHeadImg">
            <img :src="form.userHeadImg" class="avatar" />
          </el-upload>
        </div>
      </el-col>

      <el-col :span="9">
        <div class="grid-content bg-purple-light" style="margin-top: 20%">
          <el-form ref="form" :model="form" label-width="80px" :rules="rules" status-icon>
            {{"\xa0\xa0"}}<el-button type="text" @click="dialogFormVisible = true">修改密码</el-button>
            <el-form-item label="用户名称">
              <el-input v-model="form.userName"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="form.userTelphone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱地址">
              <el-input v-model="form.userEmail"></el-input>
            </el-form-item>
            <el-form-item label="个人简介">
              <el-input v-model="form.userIntro" type="textarea"></el-input>
            </el-form-item>
            <el-form-item style="text-align: left" label="用户状态">
              <el-input v-model="form.userStatus" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item style="text-align: right">

              <el-button type="primary" @click="onSubmit">修改</el-button>
            </el-form-item>

            <!-- Form -->


            <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="550px" >
              <el-form-item label="原密码" :label-width="formLabelWidth" prop="userOldPassword">
                <el-input v-model="form.userOldPassword" autocomplete="off" style="width:200px" type="password"></el-input>
              </el-form-item>
              <el-form-item label="新密码" :label-width="formLabelWidth" prop="userNewPassword1">
                <el-input v-model="form.userNewPassword1" autocomplete="off" style="width:200px" type="password"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" :label-width="formLabelWidth" prop="userNewPassword2">
                <el-input v-model="form.userNewPassword2" autocomplete="off" style="width:200px" type="password"></el-input>
              </el-form-item>

              <div slot="footer" class="dialog-footer">
                <el-button @click="clear">取 消</el-button>
                <el-button type="primary" @click="updatePassword">确 定</el-button>
              </div>
            </el-dialog>

          </el-form>
        </div>
      </el-col>

      <el-col :span="6">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>
  </div>
</template>



<script>
  import {
    findById
  } from "@/api/user";
  import {
    updateUser
  } from "@/api/user";
  import {
    uploadPicture
  } from "@/api/user";
  import {
    updateUserPassword
  } from "@/api/user";

  export default {
    data() {
      var userNewPassword1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.form.userNewPassword1 !== '') {
            this.$refs.form.validateField('checkPass');
          }
          callback();
        }
      };
      var userNewPassword2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.userNewPassword1) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        checkPass: '',
        form: {
          userId: "",
          userName: "",
          userTelphone: "",
          userEmail: "",
          userHeadImg: "",
          userIntro: '',
          userStatus: '',
          userOldPassword: '',
          userNewPassword1: '',
          userNewPassword2: ''
        },
        formPasswords:{
          userId:'',
          oldPassword:'',
          checkPassword:'',
          newPassword:''
        },
        formInline: {
          userId: this.$store.getters.userId,
          userName: "frank",
        },
        formLabelWidth: '120px',
        dialogFormVisible: false,
        rules: {
          "userOldPassword": [{
            required: true,
            message: "内容不为空",
            trigger: "blur",
          }, ],
          "userNewPassword1": [{
            validator: userNewPassword1,
            trigger: "blur",
          }, ],
          "userNewPassword2": [{
            validator: userNewPassword2,
            trigger: "blur",
          }, ],
        }
      };
    },

    created() {
      this.getData();
    },

    methods: {
      //将个人信息显示在首页
      getData() {
        findById(this.formInline.userId)
          .then((res) => {
            this.form.userId = res.data.userId;
            this.form.userName = res.data.userName;
            this.form.userTelphone = res.data.userTelphone;
            this.form.userEmail = res.data.userEmail;
            this.form.userHeadImg = res.data.userHeadImg;
            if (res.data.userStatus == 1) {
              this.form.userStatus = "正常"
            } else {
              this.form.userStatus = "冻结"
            }
            this.form.userIntro = res.data.userIntro

          })
          .catch((err) => {
            console.log(err);
            alert("后端有错！");
          });
      },

      //头像上传
      uploadHeadImg(param) {
        const formdata = new FormData();
        formdata.append("id", this.form.userId);
        formdata.append("file", param.file);
        uploadPicture(formdata).then((res) => {
          if (res.code == 200) {
            this.updatesuccess(res.message);
            this.form.userHeadImg = res.data;
            console.log(res);
          }
        });
      },

      //修改个人中心提交方法
      onSubmit() {
        this.$confirm("确认修改个人信息吗", '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateUser(this.form).then((res) => {
            if (res.code == 200) {
              this.updatesuccess(res.message);
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: "已取消修改"
          })
        })

      },
      updatePassword(){
        this.formPasswords.userId = this.form.userId
        this.formPasswords.oldPassword = this.form.userOldPassword
        this.formPasswords.newPassword = this.form.userNewPassword2
          updateUserPassword(this.formPasswords).then((res) =>{
            if(res.code == 200){
              this.$router.push({
                name:"Login"
              })
              this.$message({
              type: 'success',
              message: "密码修改成功,请重新登陆"
          })
            }else{
              this.$message({
                type:'error',
                message:'原密码错误'
              })
            }
          }).catch(() =>{
            this.$message({
              type: 'error',
              message: "密码修改错误"
          })
        })
      },

      clear(){
        this.form.userOldPassword='',
        this.form.userNewPassword1='',
        this.form.userNewPassword2='',
        this.dialogFormVisible=false
      },

      //消息提示
      updatesuccess(message) {
        this.$message({
          message: message,
          type: "success",
        });
      },

      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
    },
  };

</script>

<style>
  .myinfo {
    width: 80%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    height: 100%;
  }

  .myinfo .el-row {
    justify-content: space-between;
    padding: 0 20px;
  }

  .myinfo .avatar-box {
    margin-top: 50px;
    margin-left: 50px;
  }

  .avatar-box {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .avatar-box .el-button {
    margin-top: 20px;
  }

  .myinfo .el-avatar img {
    width: 160px !important;
    height: 220px !important;
    object-fit: none !important;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150;
    line-height: 150px;
    text-align: center;
  }

  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }

</style>
